<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.payingMember')">
              <a-select :placeholder="$t('financialManagement.selectPayingMember')" v-decorator="[ 'organId', validatorRules.organId ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <a-select-option v-for="(item,index) in retailList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item> -->
            <a-form-item :label="$t('reportQuery.supplier')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('manuManagement.selectSupplier')" showSearch
                    :dropdownMatchSelectWidth="false" v-decorator="[ 'organId', validatorRules.organId ]" optionFilterProp="children">
                    <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
          </a-col>
          
          <!-- 关联订单 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.relatedOrder')" data-step="3"
              :data-title="$t('popup.relatedOrder')" :data-intro="$t('popup.purchaseReceiptAfterOrder')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAssociated')" v-decorator="['number',validatorRules.number]"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>

          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'tenantId']" :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'custom5']" :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 单据编号 -->
          
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['billNo',validatorRules.billNo]" disabled
              :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')"
              data-step="2" :data-title="$t('setailManagement.documentNo')"
              :data-intro="$t('popup.theNumberIsGenerated')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['depotId']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.notesToDocuments')">
              <a-input :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="accountTable.loading"
          :columns="accountTable.columns"
          :dataSource="accountTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          @deleted="calcTotalPrice"
          @inputPurchaseValueChange="onChange"
          @valueChange="onValueChange">
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.totalAmount')">
              <a-input :placeholder="$t('popup.pleaseTotalCollection')" v-decorator.trim="[ 'totalPrice' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountPayment')">
              <a-input :placeholder="$t('popup.pleasePaymentAmount')" v-decorator.trim="[ 'changeAmount' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.payables')">
              <a-input :placeholder="$t('popup.pleasePaymentAmount')" v-decorator.trim="[ 'payables' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup } from '@/api/api'
  import LinkBillList from '@/views/bill/dialog/LinkBillList'
  import PersonModal from '../../system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  export default {
    name: "AdvanceInModal",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      LinkBillList,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        supList: [],
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        prefixNo: 'FYF',
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
            { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
            { title: this.$t('popup.titleOfAccount'),key: 'accountId',width: '20%', type: FormTypes.select, placeholder: this.$t('inPrint.pleaseTnter')+'${title}', options: [],
              allowSearch:true, validateRules: [{ required: true, message:'${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.amount'),key: 'eachAmount', width: '10%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}',
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.remarks'),key: 'remark', width: '30%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
                // 租户id
            { title: this.$t('reportQuery.remarks'),key: 'tenantId', width: '30%', type: FormTypes.hidden, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('reportQuery.remarks'),key: 'custom5', width: '30%', type: FormTypes.hidden, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            ]
        },
        confirmLoading: false,
        validatorRules:{
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleasePaymentMember')+'!' }
            ]
          },
          handsPersonId:{
            rules: [
              { required: true, message:this.$t('popup.pleaseSelectPersonnel')+'!'}
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
          billNo:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          },
          number:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAssociated') }
            ]
          }
        },
        url: {
          add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        console.log('this.fileList :>> ', this.fileList);
        this.initSupplier()
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark','creator','userName','number','custom5','tenantId',
                  'totalPrice', 'changeAmount'))
            this.form.setFieldsValue({
              depotId:this.model.custom5 ? this.model.depotId :''
            })
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initRetail()
        this.initPerson()
        this.initDetailAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectSup({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      onSearchLinkNumber() {
        let organId = this.form.getFieldValue('organId')
        this.$refs.linkBillList.acceptanceShow('其它', '采购订单', this.$t('warehouseManagement.supplier'), '1,2,3', organId, this.prefixNo)
        this.$refs.linkBillList.title = this.$t('popup.selectPurchaseOrder')
      },
      linkBillListOk(selectBillDetailRows) {
        const selectedItem = selectBillDetailRows[0]
        this.rowCanEdit = false
        // this.materialTable.columns[2].type = FormTypes.select
        if(selectBillDetailRows && selectBillDetailRows.length>0) {
          let discountLastMoney = 0
          this.$nextTick(() => {
            this.form.setFieldsValue({
              'number': selectedItem.number,
              'tenantId':selectedItem.tenantId
            })
          })
          if (!selectedItem.eachAmount) selectedItem.eachAmount = selectedItem.totalPrice
          this.accountTable.dataSource = selectBillDetailRows
          this.$nextTick(() => {
            this.form.setFieldsValue({
              'organId': selectedItem.organId,
              'payables':selectedItem.eachAmount,
              'changeAmount':selectedItem.eachAmount,
              'totalPrice':selectedItem.eachAmount,
              'depotId': selectedItem.custom5 ? selectedItem.depotId :'',
              'custom5':selectedItem.custom5,
            })
          })
        }
      },
      calcTotalPrice () {
        const table = this.$refs[this.refKeys[0]]
        table.getValues((err, values) => {
          let totalPrice = values.reduce((total,item)=>{
            return this.__addition(total, item.eachAmount)
          },0)
          this.form.setFieldsValue({
            'totalPrice': totalPrice,
            'changeAmount': totalPrice
          })
        }) 
      },
      onChange(event){
        console.log(event);
        const { type, row, column, value, target } = event
        switch (column.key) {
          case 'eachAmount':
          this.calcTotalPrice()
          break;
        }
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '预付款单'
        for(let item of detailArr){
          totalPrice += item.eachAmount-0
        }
        billMain.totalPrice = 0-totalPrice
        billMain.changeAmount = 0-billMain.changeAmount
        billMain.creator = this.$attrs.userList.find(item => item.userName === billMain.userName).id
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>